//
//  PlayViewController.m
//  HimalayaMusic
//
//  Created by dllo on 16/1/13.
//  Copyright © 2016年 WXCLegendary. All rights reserved.
//

#import "PlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "HeadView.h"
@interface PlayViewController () <HeadViewDelegate>
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) HeadView *headView;
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) UIImageView *scrollImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *scrollImageViewTimer;
@property (nonatomic, strong) UILabel *timeLable;
@property (nonatomic, strong) UILabel *currentTimeLable;
@property (nonatomic, strong) UISlider *volumeSlider;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, assign) BOOL playing; // 判断是否正在播放
@property (nonatomic, strong)UILabel *scrollLabel;

@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, assign)CGRect tagRect;

@property (nonatomic, strong) STKAudioPlayer *player;
@end

@implementation PlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){.flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000}}];
    [self playMusic];
    [self createBackView];
    
    // 进入视图正在播放
    self.playing = YES;
    [self createScrollView];
}
 //滚动效果
- (void)viewWillAppear:(BOOL)animated {
    
    [self scrollAction];
}

#pragma mark - 创建视图
- (void)createBackView
{
    self.headView = [[HeadView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
    self.headView.delegate = self;
    
    // 背景图片
    self.backImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    self.backImageView.image = [UIImage imageNamed:@"Untitled"];
    // 上部分高亮显示
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = CGRectMake(0, 0, self.backImageView.frame.size.width, self.backImageView.frame.size.height);
   
    [self.backImageView addSubview:effectView];
    
    [self.view addSubview:self.backImageView];
    [self.view addSubview:self.headView];
    // 圆形图片
    self.scrollImageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 100, CGRectGetWidth(self.view.bounds) - 80, CGRectGetWidth(self.view.bounds) - 80)];

    /**
     *  设置图片
     */
    [self.scrollImageView sd_setImageWithURL:[NSURL URLWithString:[self.dataSource[self.sequence] coverMiddle]]];
    
    self.scrollImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.scrollImageView];
    self.scrollImageView.layer.cornerRadius = (CGRectGetWidth(self.view.bounds) - 80) / 2;
    self.scrollImageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.scrollImageView.layer.borderWidth = 2;
    self.scrollImageView.layer.masksToBounds = YES;
    [self.view addSubview:self.scrollImageView];
    // 圆形图片转动
    self.scrollImageViewTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(scrollImageViewTimer:) userInfo:nil repeats:YES];
    
    
    
    
    
    
    //声音slider
    self.volumeSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, UIScreen_WIDTH - 100, 20)];
    self.volumeSlider.center = CGPointMake(kControlBarCenterX, kControlBarCenterY + 60);
    [self.volumeSlider setThumbImage:[UIImage imageNamed:@"volumn_slider_thumb"] forState:UIControlStateNormal];
    // 最大音量
    self.volumeSlider.maximumValue = 1;
    self.volumeSlider.minimumValueImage = [UIImage imageNamed:@"volumelow"];
    self.volumeSlider.maximumValueImage = [UIImage imageNamed:@"volumehigh"];
    // 初始音量
    self.volumeSlider.value = 0.5;
    self.volumeSlider.minimumTrackTintColor = [UIColor blackColor];
    [self.volumeSlider addTarget:self action:@selector(changeVolumeSlider:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.volumeSlider];
    
    // 播放进度条
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, UIScreen_WIDTH - 100, 20)];
    self.slider.center = CGPointMake(kControlBarCenterX, kControlBarCenterY + 10);
    [self.slider setThumbImage:[UIImage imageNamed:@"volumn_slider_thumb"] forState:UIControlStateNormal];
    self.slider.minimumTrackTintColor = [UIColor blackColor];
    self.slider.minimumValue = 0.0;
    self.slider.maximumValue = 1.0;
        [self.slider addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];

    
    //当前播放时间label
    self.currentTimeLable = [[UILabel alloc] initWithFrame:CGRectMake(self.slider.frame.origin.x - 5 - 38, self.slider.frame.origin.y, 50, 20)];
    self.currentTimeLable.text = @"00:00";
    self.currentTimeLable.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:self.currentTimeLable];
    
    //总时间label
    self.timeLable = [[UILabel alloc] initWithFrame:CGRectMake(self.slider.frame.origin.x + self.slider.frame.size.width, self.slider.frame.origin.y, 50, 20)];
    self.timeLable.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:self.timeLable];
    
//     播放的button
    self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.playButton.frame = CGRectMake(160 * kWidth, self.view.frame.size.height - 110, 50 * kWidth, 50 * kWidth);
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
    [self.playButton addTarget:self action:@selector(playButton:) forControlEvents:UIControlEventTouchUpInside];
    self.playButton.tag = 520;
    [self.view addSubview:self.playButton];
    
    //上一曲的button
    UIButton *buttonUp = [UIButton buttonWithType:UIButtonTypeSystem];
    buttonUp.frame = CGRectMake(60 * kWidth, self.view.frame.size.height - 100, 30 * kWidth, 30 * kWidth);
    [buttonUp setBackgroundImage:[UIImage imageNamed:@"shangyishou"] forState:UIControlStateNormal];
    [buttonUp addTarget:self action:@selector(playUp:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonUp];
    
    
    //下一曲的button
    UIButton *buttonNext = [UIButton buttonWithType:UIButtonTypeSystem];
    buttonNext.frame = CGRectMake(280 * kWidth, self.view.frame.size.height - 100, 30 * kWidth, 30 * kWidth);
    [buttonNext setBackgroundImage:[UIImage imageNamed:@"xiayishou"] forState:UIControlStateNormal];
    [buttonNext addTarget:self action:@selector(playNext:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonNext];

}

/**
 *  顶部滚动效果
 *
 */
#warning 滚动效果

- (void)createScrollView {
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    self.scrollView.center = CGPointMake(self.view.width / 2, 42);
    [self.view addSubview:self.scrollView];
    self.scrollLabel = [[UILabel alloc] init];
    self.scrollLabel.font = [UIFont systemFontOfSize:15];
    self.scrollLabel.text = [self.dataSource[self.sequence] title];


    //标题做成自适应宽度
    
    
    [self.scrollView addSubview:self.scrollLabel];
    [self scrollAction];
    
    
}

- (void)scrollAction {
    NSDictionary *scrollLabelDic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    self.tagRect = [self.scrollLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:scrollLabelDic context:nil];
    self.scrollLabel.frame = CGRectMake(0, 0, self.tagRect.size.width, 30);
    [UIView animateWithDuration:3 animations:^{
        [UIView setAnimationRepeatCount:2000000];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationRepeatAutoreverses:YES];
        self.scrollLabel.transform = CGAffineTransformTranslate(self.scrollLabel.transform, self.scrollView.width - self.scrollLabel.width, 0);
    }];
}









//显示音轨
-(void)track
{
    self.slider.maximumValue = self.player.duration;//音乐总共时长
    self.slider.value = self.player.progress;//当前进度
    //当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    self.currentTimeLable.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)proMin, (long)proSec];
    self.timeLable.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)durMin, (long)durSec];
    
    if (self.player.duration - self.player.progress <= 2 && self.player.progress > 0) {
        if (self.sequence + 1 == self.dataSource.count) {
            self.sequence = 0;
        } else {
            self.sequence++;
        }
        [self playMusic];
    }
}

//拖动进度条

- (void)progressAction:(UISlider *)sender {
    if (self.player) {
        [self.player seekToTime:sender.value];
    }
}

//上一曲

- (void)playUp:(UIButton *)sender {
    if (self.dataSource.count) {
        if (self.sequence == 0) {
            self.sequence = self.dataSource.count - 1;
        } else {
            self.sequence--;
        }
        [self playMusic];
    }
    [self.scrollImageView sd_setImageWithURL:[NSURL URLWithString:[self.dataSource[self.sequence] coverMiddle]]];
    self.scrollLabel.text = [self.dataSource[self.sequence] title];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
    
    
}

//下一首

- (void)playNext:(UIButton *)sender {
    
    if (self.dataSource.count) {
        if (self.sequence + 1 == self.dataSource.count) {
            self.sequence = 0;
        } else {
            self.sequence++;
        }
        [self playMusic];
    }
    [self.scrollImageView sd_setImageWithURL:[NSURL URLWithString:[self.dataSource[self.sequence] coverMiddle]]];
    self.scrollLabel.text = [self.dataSource[self.sequence] title];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
}

#pragma 创建播放器单例
+ (PlayViewController *)sharePlayViewController {
    static PlayViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[PlayViewController alloc] init];
    });
    return player;
}

//数组set方法

- (void)setDataSource:(NSArray *)dataSource {
    if (_dataSource != dataSource) {
        _dataSource = dataSource;
    }
     [self playMusic];
      self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
}




#pragma mark - 圆形图片转动
- (void)scrollImageViewTimer:(NSTimer *)timer {
    self.scrollImageView.transform = CGAffineTransformRotate(self.scrollImageView.transform, 0.01);
}

#pragma mark - 控制声音大小
- (void)changeVolumeSlider:(UISlider *)slider
{
    [self.player setVolume:slider.value];
}

#pragma mark - 播放歌曲
- (void)playMusic {
    if ([self.dataSource[self.sequence] playUrl64] != self.currentURL) {
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_async(mainQueue, ^{
            [self.player play:[self.dataSource[self.sequence] playUrl64]];
            self.currentURL = [self.dataSource[self.sequence] playUrl64];
        });
    }
}

#pragma mark - 播放按钮
- (void)playButton:(UIButton *)button {
    
    self.playing = !self.playing;
    if (self.playing) {
        [self.scrollImageViewTimer setFireDate:[NSDate distantPast]];
        [self resume];
        
        [button setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
        
    } else {
        
        [self.scrollImageViewTimer setFireDate:[NSDate distantFuture]];
        [self pause];
        [button setBackgroundImage:[UIImage imageNamed:@"bofang@2x"] forState:UIControlStateNormal];
    }
}

#pragma - mark headView协议方法 返回上一页
- (void)disMissController {
    
    [self dismissViewControllerAnimated:YES completion:^{
       
        
        
        
    }];
}


#pragma mark - 继续
- (void)resume{
    [self.player resume];
}

#pragma mark - 暂停
- (void)pause{
    [self.player pause];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
